package com.xty.xtyle.detail;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.xty.xtyle.R;
import com.xty.xtyle.db.ClothTypes;
import com.xty.xtyle.db.ClothTypesDao;
import com.xty.xtyle.db.User;
import com.xty.xtyle.db.UserDao;
import com.xty.xtyle.db.cloth.Cloth;
import com.xty.xtyle.db.cloth.ClothDao;
import com.xty.xtyle.picture.PickPhotoDialog;
import com.xty.xtyle.utils.CommonUtil;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

import static org.litepal.LitePalApplication.getContext;


public class ClothDetailActivity extends AppCompatActivity  implements EasyPermissions.PermissionCallbacks  {
    EditText edit_brand, edit_color, edit_material, edit_size, edit_session, edit_status, edit_price, edit_type;
    ImageView imageView;
    String clothPath;
    Cloth cloth;
    /**
     * 如果为空，表示普通增加衣服
     * 如果不为空，表示用户自行添加衣服到自己的衣架
     * @param id  衣服的数据库id，通过首页进入
     */
    public static void startActivity(Context context, int id) {
        Intent intent = new Intent(context, ClothDetailActivity.class);
        if (id > -1) intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cloth_detail);

        initBar();
        initCloth();

    }

    void initBar() {
        findViewById(R.id.left_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.cloth_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addCloth();
            }
        });
        findViewById(R.id.cloth_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPermission();
            }
        });
        findViewById(R.id.right_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AddClothActivity.startActivity(view.getContext(), "");
            }
        });
        TextView titleView = findViewById(R.id.center_icon);
        titleView.setText("详情");
    }

    //通过传递过来的id从数据库读取数据
    void initCloth() {
        edit_brand = findViewById(R.id.edit_brand);
        edit_color = findViewById(R.id.edit_color);
        edit_material = findViewById(R.id.edit_material);
        edit_size = findViewById(R.id.edit_size);
        edit_session = findViewById(R.id.edit_session);
        edit_status = findViewById(R.id.edit_status);
        edit_price = findViewById(R.id.edit_price);
        edit_type = findViewById(R.id.edit_type);
        imageView = findViewById(R.id.cloth_icon);

        Intent intent = getIntent();
        int id = intent.getIntExtra("id", -1);
        ClothDao dao = new ClothDao();
        cloth = dao.findCloth(id);
        if (null == cloth) return;
        edit_brand.setText(cloth.getBrand());
        edit_color.setText(cloth.getColor());
        edit_material.setText(cloth.getMaterial());
        edit_size.setText(cloth.getSize());
        edit_session.setText(cloth.getSession());
        edit_status.setText(cloth.getStatus());
        edit_price.setText(cloth.getPrice());
        String type = cloth.getType() == null ? "" : cloth.getType();
        edit_type.setText(type);
        loadImage(cloth.getImage());

    }

    void loadImage(String imagePath) {
        clothPath = imagePath;
        Glide.with(this).load(imagePath).into(imageView);
    }


    //添加衣服到数据库
    void addCloth() {
        String brand = edit_brand.getText().toString();
        String color = edit_color.getText().toString();
        String material = edit_material.getText().toString();
        String size = edit_size.getText().toString();
        String session = edit_session.getText().toString();
        String status = edit_status.getText().toString();
        String price = edit_price.getText().toString();
        String type = edit_type.getText().toString();

        if (null == cloth) return;
        cloth.setBrand(brand);
        cloth.setColor(color);
        cloth.setMaterial(material);
        cloth.setSize(size);
        cloth.setSession(session);
        cloth.setStatus(status);
        cloth.setPrice(price);
        cloth.setType(type);
        if (TextUtils.isEmpty(clothPath)){
            CommonUtil.showToast("请选择图片");
            return;
        }
        cloth.setImage(clothPath);
        checkType(type);
        //如果type不为空，表示首页进入
        if (!TextUtils.isEmpty(type)) {
            cloth.setType(type);
            //如果空的，表示用户给自己衣架添加
        } else {
            UserDao dao = new UserDao();
            User user = dao.findFirst();
            if (null != user) cloth.setUserName(user.getName());
        }
        cloth.save();

        CommonUtil.showToast("保存成功");
    }

    /**
     * 如果类型没有，则添加
     * @param type
     */
    void checkType(String type) {
        if (!TextUtils.isEmpty(type)) {
            ClothTypesDao clothTypesDao = new ClothTypesDao();
            ClothTypes types = clothTypesDao.findClothType(type);
            if (null == types) {
                ClothTypes clothTypes = new ClothTypes(type);
                clothTypes.save();
            }
        }
    }

    PickPhotoDialog pickPhotoDialog;
    private void showDialog() {
        pickPhotoDialog = new PickPhotoDialog();
        pickPhotoDialog.show(getSupportFragmentManager(), "pick");
        pickPhotoDialog.setCallBack(new PickPhotoDialog.CallBack() {
            @Override
            public void pictureBack(String imagePath) {
                Log.d("FlutterPush", "back  imageFile:"+imagePath);
                if (!TextUtils.isEmpty(imagePath))
                    loadImage(imagePath);
            }
        });
    }

    //拍照,图片存储/读取都要权限
    private void checkPermission() {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            showDialog();
        } else {
            //权限拒绝 申请权限
//            EasyPermissions.requestPermissions(this, getString(R.string.permission_rationale_message), 101, perms);
            ActivityCompat.requestPermissions(this, perms, 102);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //获取的权限一定要是读取存储和照相
        String[] permss = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getContext(), permss)) {
            showDialog();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }
}
